<template>
  <div class="gotop"
  	 	 v-show="isShow"
  	 	 :data-threshold="threshold"
  	 	 @click="onClickHandle"></div>
</template>


<script>
export default {
    data () {
        return {
            isShow:false
        }
    },
    props:{
        threshold:{
            type:Number,
            default:500
        }
    },
    mounted (){
        this.init();
    },
    methods:{
        onClickHandle () {
            var self = this;
            document.body.scrollTop = 0;
            document.documentElement.scrollTop = 0;
            self.isShow=false;
        },
        init () {
            var self = this;
            var threshold=self.threshold;
            var throttleScroll = self.throttle(function(e) {
            	var scrTop=document.body.scrollTop || document.documentElement.scrollTop;
            	if(scrTop > threshold){
            		self.isShow=true
            	}else{
            		self.isShow=false
            	}
            }, 100)
            window.addEventListener('scroll',function(e){
            		throttleScroll(e);
            });
        },
        throttle (func, delay) {
            var timeout = null
		        var lastRun = 0
		        return function () {
		            if (timeout) {
		                return
		            }
		            var elapsed = +new Date() - lastRun
		            var context = this
		            var args = arguments
		            var runCallback = function runCallback () {
		                lastRun = +new Date()
		                timeout = false
		                func.apply(context, args)
		            }
		
		            if (elapsed >= delay) {
		                runCallback()
		            } else {
		                timeout = setTimeout(runCallback, delay)
		            }
		        }
        },
    }
}
</script>

<style scroped>
    .gotop{
        display: block;
        position: fixed;
        z-index: 999;
        width:1.2rem;
        height: 1.2rem;
        right: .373333rem;
        bottom: .373333rem;
        -webkit-tap-highlight-color:#fff;
        background:url(../../assets/img/common/sprite_gray.png) no-repeat;
        background-size: 1.2rem 1.2rem;
    }
</style>
